<?php

namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Cart;
use app\common\model\Goodorder;
use app\common\model\member\Category;
use app\common\model\member\product\Specs;
use app\common\model\Occupants;
use app\common\model\Ordersessions;
use app\common\model\Rooms;
use app\manystore\model\Categories;
use app\manystore\model\ManystoreShop;
use app\manystore\model\Spece;
use think\Db;

/**
 * 会员商城
 */
class Memproducts extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\member\Products();
    }

    public function category(){
      $categorise=  Category::where('status',1)->field('id,name,image')->select();
        $this->success('请求成功', $categorise);
    }


    public function products_list()
    {
        $where = []; // 初始化查询条件数组

        if(input('type_id')!==null&&input('type_id')!==''){
            $where['category_id']=input('type_id');
        }
        if(input('is_hot')!==null&&input('is_hot')!==''){
            $where['is_hot']=input('is_hot');
        }

        $query = \app\common\model\member\Products::where('status' ,'=',1);
        if (!empty($where)) {
            $query = $query->where($where);
        }

        // 获取排序参数
        $sort = input('sort');
        $order = input('order', 'desc');

        // 根据排序参数进行排序
        switch ($sort) {
            case 'sales':
                $query = $query->order("sales $order");
                break;
            case 'latest':
                $query = $query->order("createtime $order");
                break;
            case 'price':
                $query = $query->order("price $order");
                break;
            default:
                $query = $query->order('weigh desc');
                break;
        }
        $list = $query
            ->field('id, name, image,price')
            ->paginate(10);
        $this->success('请求成功', $list);
    }

    public function products_info(){
        $info=\app\common\model\member\Products::where('id',input('id'))->field('id,carousel,video_url,description,price,sales,stock,name,has_specs,image,postage')->find();
        if($info){
            $imagesArray = explode(',', $info['carousel']);
            $resultArray = [];
            foreach ($imagesArray as $url) {
                $resultArray[] = ['image' => trim($url)]; // 使用 trim 去除多余的空格
            }
            $info['carousel']=$resultArray;
            $info['video_url']=$info['video_url']==""?[]:explode(',', $info['video_url']);
            if($info['has_specs']==1){
                $info['sales']=Specs::where('product_id',$info['id'])->sum('sales');
            }
        }
        $this->success('请求成功', $info);
    }

    /*
     * 规格列表
     */
    public function specs(){
        $specs=Specs::where('product_id',input('id'))->field('id,spec_name,price')->select();
        $this->success('请求成功', $specs);
    }

    /*
     * 购物车列表
     */

    public function Cart_list(){
        $cartItems = Cart:: field('id,num,spec_id')->with('memproduct')
            ->where('cart.user_id', $this->auth->id)
            ->where('cart.type', 0)
            ->where('cart.status', 0)
            ->where('memproduct.status', '1')
            ->whereNull('memproduct.deletetime')
            ->select();
        $validItems = [];
        $num=0;
        foreach ($cartItems as $item){
            $item->getRelation('memproduct')->visible(['id','price','image','name']);
            if($item['spec_id']!=null){
                $Specs= Specs::where('id','=',$item['spec_id'])->find();
                if($Specs==null){
                    continue; // 如果规格为 null，跳过当前循环
                }else{
                    $item->Specs=$Specs['spec_name'];
                    $item->memproduct->price=$Specs['price'];
                }

            }
            $validItems[] = $item;
            $num+=$item->num;
        }
        return json(['code'=>1,'msg'=>'请求成功','time'=>time(),'data'=>$validItems,'num'=>$num]);

    }





    /*
     * 加入购物车
     */

    public function add_cart(){
        if (!$product_id= input('product_id')) {
            $this->error(__('请选择商品'));
        }
        if (!$num= input('num')) {
            $this->error(__('请选择数量'));
        }
        $cartItem = Cart::where('user_id', $this->auth->id)
            ->where('product_id', $product_id)
            ->where('spec_id',input('spec_id'))
            ->where('type',0)
            ->find();
        if ($cartItem) {
            $cartItem->num += $num;
            $cartItem->save();
        }else{
            Cart::create([
                'user_id'=>$this->auth->id,
                'product_id'=>$product_id,
                'spec_id'=>input('spec_id') ? input('spec_id') : null,
                'type'=>0,
                'num'=>input('num'),
            ]);
        }

        $this->success('请求成功', []);
    }


    public function add_good_order(){

     $occupants=  occupants::where('id','=',input('occupants_id'))->find();
     if($occupants['status']!==0){
         $this->error('当前订单已结束');
     }

        $jsonString = htmlspecialchars_decode(input('goodinfo'));
        $array = json_decode($jsonString, true);
        db::startTrans();

       $Ordersessions= Ordersessions::create([
           'occupants_id'=>$occupants['id'],
           'user_id'=>$this->auth->id,
           ]);

        foreach ($array as $item){
            $Products=\app\common\model\Products::where('id',$item['goodid'])->find();
            //多规格
            $has_specs=0;
            if($item['spec_id']!=null&&$item['spec_id']!=''){
               $Spece= Spece::where('id',$item['spec_id'])->find();
               $has_specs=1;
            }
            $price=$Spece?$Spece['price']:$Products['price'];
            Goodorder::create([
                'occupants_id'=>$occupants['id'],
                'order_session_id'=>$Ordersessions->id,
                'goodimage'=>$Products['image'],
                'goodname'=>$Products['name'],
                'price'=>$price,
                'goodid'=>$item['goodid'],
                'spec'=>$has_specs==1?$Spece['spec_name']:'常规',
                'num'=>$item['num'],
                'total'=>$item['num']*$price
            ]);
            if($has_specs==0){
               $result= \app\common\model\Products::where('id',$item['goodid'])->where('stock','=',$Products['stock'])->setDec('stock',$item['num']);
            }else{
              $result=  Spece::where('id',$item['spec_id'])->where('stock','=',$Spece['stock'])->setDec('stock',$item['num']);
            }
            if($result==0){
                db::rollback();
                $this->error('商品库存不足');

            }
        }
        db::commit();

        $room=Rooms::where('id',$occupants['room_id'])->find();

        $notice=new Notice();
        $notice->Notice($occupants['room_id'],$occupants['shop_id'],$occupants['id'],$room['room_number']. "房间购买商品",$occupants['shop_id']);

        $this->success('请求成功', []);
    }




}
